import { IQueryObject } from 'tiny-entity2/queryObject';
import { Transaction } from "tiny-entity2";
import { ApiDataContext } from "../domain/apiDataContext";
import { DataChangeLog } from "../domain/models/dataChangeLog";
import { BaseService } from "./baseService";

export class DataChangeLogService extends BaseService {
    CreateDataChangeLog(entity: DataChangeLog, ctx?: ApiDataContext) {
        ctx || (ctx = new ApiDataContext());
        return Transaction(ctx, async (ctx) => {
            let d = new DataChangeLog();
            d.ConverToEntity(entity);
            return ctx.Create(d);
        });
    }
    UpdateDataChangeLog(entity: DataChangeLog, ctx?: ApiDataContext) {
        ctx || (ctx = new ApiDataContext());
        return Transaction(ctx, async (ctx) => {
            let d = new DataChangeLog();
            d.ConverToEntity(entity);
            return ctx.Update(d);
        });
    }
    GetDataChangeLogById(id: string) {
        let ctx = new ApiDataContext();
        return ctx.DataChangeLog.First(x => x.id == $args1, { $args1: id });
    }
    QueryDataChangeLog(params: DataChangeLogQueryParams) {
        let ctx = new ApiDataContext();
        let q = ctx.DataChangeLog as IQueryObject<DataChangeLog>;
        if (params) {
            if (params.dataRegisterId) {
                q = q.Where(x => x.dataRegisterId == $args1, { $args1: params.dataRegisterId });
            }
            if (params.status) {
                q = q.Where(x => x.status == $args1, { $args1: params.status });
            }
            if (params.flowNodeId) {
                q = q.Where(x => x.flowNodeId == $args1, { $args1: params.flowNodeId });
            }
        }

        return q.OrderByDesc(x => x.updateTime).ToList();
    }
}

export interface DataChangeLogQueryParams {
    status?: string;
    dataRegisterId?: string;
    orgId?: string;
    flowNodeId?: string;
}